﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SystemCenter.Orchestrator.Integration;
using RestSharp;

namespace SocialMediaIntegrationPack
{
    [Activity("Yammer Messages Monitor")]
    [ActivityMonitor(Interval = 60)]
    public class YammerMessagesMonitorAct : YammerGetMessagesAct
    {

        private readonly string pname_newer_than = "newer_than";

        private long lastId = -1;
        private DateTime startTime;

        public YammerMessagesMonitorAct()
        {
            startTime = DateTime.Now; //remembering for filter
        }

        protected override void AddRequestExtraParameters(RestRequest r)
        {
            base.AddRequestExtraParameters(r);
            if (lastId > 0)
            {
                r.AddParameter(pname_newer_than, lastId);
            }
        }

        /// <summary>
        /// getting messages newer than lastID (newer than StartTime - the very first time)
        /// </summary>
        /// <param name="lst"></param>
        /// <returns></returns>
        protected override List<YammerMessage> FilterMessages(List<YammerMessage> lst)
        {
            List<YammerMessage> r;
            if (lastId <= 0)
            {
                r = (from ym in lst
                     where DateTime.Parse(ym.CreatedAt) > startTime
                     select ym).ToList();
            }
            else
            {
                r = lst;
            }
            if (r.Count > 0)
            {
                lastId = r[0].Id;
            }
            return r;
        }
    }
}